package com.lyc.api.service;

import com.lyc.api.exception.BookException;
import com.lyc.common.enums.ResultEnum;
import com.lyc.common.model.BookCollect;
import com.lyc.common.model.BookInfo;
import com.lyc.common.repository.BookCollectRepository;
import com.lyc.common.repository.BookInfoRepository;
import com.lyc.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 廖师兄
 * 2017-05-29 17:44
 */
@Service
public class BookCollectService {

    @Autowired
    private BookCollectRepository bookCollectRepository;

    @Autowired
    private BookInfoRepository bookInfoRepository;

    @Autowired
    private BookService bookService;

    public List<BookCollect> list(String uid) {
        List<BookCollect> bookCollectList = bookCollectRepository.findByUidOrderByCreateTimeDesc(uid);

        List<String> bookIdList = bookCollectList.stream()
                .map(e -> e.getBookId())
                .collect(Collectors.toList());

        List<BookInfo> bookInfoList = bookService.list(bookIdList);

        //遍历组合
        bookCollectList.stream().forEach(c -> {
            bookInfoList.stream().forEach(i -> {
                if (c.getBookId().endsWith(i.getBookId())) {
                    c.setBookName(i.getBookName());
                    c.setBookAuthor(i.getBookAuthor());
                    c.setBookImage(i.getBookImage());
                    c.setPublishTime(i.getPublishTime());
                    c.setBookDownloadUrl(i.getBookDownloadUrl());
                }
            });
        });

        return bookCollectList;
    }

    @Transactional
    public BookCollect add(String uid, String bookId) {
        BookInfo bookInfo = bookInfoRepository.findOne(bookId);
        if (bookInfo == null) {
            throw new BookException(ResultEnum.BOOK_EXIST);
        }

        //书的下载量+1
        bookService.increaseReadCount(bookInfo);

        BookCollect bookCollect = new BookCollect();
        bookCollect.setCollectId(RandomUtil.id());
        bookCollect.setUid(uid);
        bookCollect.setBookId(bookId);
        return bookCollectRepository.save(bookCollect);
    }

    public Integer delete(List<String> collectIdList) {
        return bookCollectRepository.deleteByCollectIdIn(collectIdList);
    }
}
